/*
 * Public Credit Information Sharing Platform(PCISP).
 * Copyright (c) 2019-2020 jsxzkingdee and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 * Please visit https://www.zhengxinsoft.com if you need additional information or have any questions.
 */

package com.platform.comm.validation;

import com.platform.comm.validation.constraints.CompareField;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.reflect.FieldUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.math.BigDecimal;
import java.util.Objects;

/**
 * Description: 比较验证器
 *
 * @author libin created on 2020/5/6.
 */
@Slf4j
public class CompareFieldValidator implements ConstraintValidator<CompareField, Object> {
    private String baseField;
    private String matchField;

    @Override
    public void initialize(CompareField constraintAnnotation) {
        baseField = constraintAnnotation.baseField();
        matchField = constraintAnnotation.matchField();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        try {
            Object baseFieldValue = FieldUtils.readDeclaredField(value, baseField, true);
            Object matchFieldValue = FieldUtils.readDeclaredField(value, matchField, true);
            if (Objects.nonNull(baseFieldValue) && Objects.nonNull(matchFieldValue)) {
                BigDecimal base = new BigDecimal(String.valueOf(baseFieldValue));
                BigDecimal match = new BigDecimal(String.valueOf(matchFieldValue));
                return base.compareTo(match) > 0;
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return true;
        }
        return true;
    }
}
